package nckd.wnqjt.tmc.tda.plugin.form;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

import com.alibaba.fastjson.JSON;
import kd.bos.ai.util.JsonUtil;
import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.AppInfo;
import kd.bos.entity.AppMetadataCache;
import kd.bos.entity.qing.*;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.form.IFormView;
import kd.bos.form.IPageCache;
import kd.bos.form.ShowType;
import kd.bos.form.control.IQingAnalysis;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.mvc.SessionManager;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.report.ReportShowParameter;
import kd.bos.servicehelper.QueryServiceHelper;

/**
 * @author husheng
 * @date 2024-11-04 11:55
 * @description 动态表单插件      担保人类型分布-总额
 */
public class GuaranteetypesumQingDataProvider extends AbstractFormPlugin implements IQingDataProvider {
    /**
     * 定义轻分析表头
     */
    @Override
    public QingMeta getMeta(String s) {
        String entityKey = "gm_guaranteecontract";
        QingMeta meta = new QingMeta();
        EntryEntity entity = new EntryEntity();
        entity.setKey(entityKey);
        entity.setName(new LocaleString("PK"));
        entity.setPkFieldName("id");
        meta.addEntryEntity(entity);

        Field column = new Field();
        column.setEntity(entityKey);//字段所属实体key	否
        column.setKey("id");// 字段名(唯一标识)	是
        column.setFieldType(QingFieldType.Int.toNumber()); //数据类型	是
        column.setName(new LocaleString("id")); //字段别名	是
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("orgName");
        column.setFieldType(QingFieldType.String.toNumber());
        column.setName(new LocaleString("资金组织"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("bizdate");
        column.setFieldType(QingFieldType.Date.toNumber());
        column.setName(new LocaleString("日期"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("guaranteetype");
        column.setFieldType(QingFieldType.String.toNumber());
        column.setName(new LocaleString("担保人类型"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("amount");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("总额"));
        meta.addColumn(column);

        return meta;
    }

    /**
     * 获取轻分析数据，通过拿到过滤条件可以重新定义取数逻辑
     */
    @Override
    public QingData getData(String s, int i, int i1) {
        //拿过滤条件，进行取数
        String qFilter = getPageCache().get("qFilter");
        if (qFilter != null) {
            //通过此方法拿到过滤参数
            Map<String, Object> filterParam = (Map) JSON.parseObject(qFilter, Map.class);
        }

        /**
         * 担保人类型
         * 本组织	bos_org
         * 内部组织	tmc_org
         * 银行	tmc_bank
         * 非银行金融机构	tmc_otherbank
         * 客商	bd_bizpartner
         */
        // 查询担保合同
        String guaranteecontractSql = "id,org.id orgId,org.name orgName,org.number orgNumber,bizdate," +
                "entry_guaranteeorg.id,entry_guaranteeorg.a_guaranteetype,entry_guaranteeorg.a_gamount";

        //担保结束日期>=查询日期的数据
        QFilter filter1 = new QFilter("billstatus", QCP.equals, "C")
                .and("enddate", QCP.large_equals, this.getCurrentDate());
        DataSet gmGuaranteecontract = QueryServiceHelper.queryDataSet(this.getClass().getName(), "gm_guaranteecontract", guaranteecontractSql, filter1.toArray(), null);

        //担保结束日期<查询日期且担保债务存在担保中的数据
        QFilter filter2 = new QFilter("billstatus", QCP.equals, "C")
                .and("enddate", QCP.less_than, this.getCurrentDate());
        DataSet gmGuaranteecontract2 = QueryServiceHelper.queryDataSet(this.getClass().getName(), "gm_guaranteecontract", guaranteecontractSql, filter2.toArray(), null);
        QFilter gQF = new QFilter("billstatus", QCP.equals, "C")
                .and("gdebtstartdate", QCP.less_equals, this.getCurrentDate())
                .and("gratio", QCP.not_equals, BigDecimal.ZERO)
                .and("gdebtbalance", QCP.not_equals, BigDecimal.ZERO)
                .and(new QFilter("gsrcbilltype", QCP.not_equals, "cdm_payablebill")
                        .or("gdebtenddate", QCP.is_null, null)
                        .or("gdebtenddate", QCP.large_than, this.getCurrentDate()));
        DataSet gcUseBills = QueryServiceHelper.queryDataSet(this.getClass().getName(), "gm_guaranteeuse", "id,gcontract.id gcontractId", gQF.toArray(), null);
        DataSet finish = gmGuaranteecontract2.join(gcUseBills).on("id", "gcontractId").select(gmGuaranteecontract2.getRowMeta().getFieldNames()).finish();

        // 根据担保人类型分类
        DataSet guaranteecontractIn = gmGuaranteecontract.copy().filter("entry_guaranteeorg.a_guaranteetype in ('bos_org','tmc_org')");
        DataSet guaranteecontractOut = gmGuaranteecontract.copy().filter("entry_guaranteeorg.a_guaranteetype not in ('bos_org','tmc_org')");
        DataSet guaranteecontractIn2 = finish.copy().filter("entry_guaranteeorg.a_guaranteetype in ('bos_org','tmc_org')");
        DataSet guaranteecontractOut2 = finish.copy().filter("entry_guaranteeorg.a_guaranteetype not in ('bos_org','tmc_org')");

        DataSet inDataSet = guaranteecontractIn.select(new String[]{"id", "orgName", "bizdate", "entry_guaranteeorg.id", "entry_guaranteeorg.a_gamount amount", "'集团内' as guaranteetype"});
        DataSet outDataSet = guaranteecontractOut.select(new String[]{"id", "orgName", "bizdate", "entry_guaranteeorg.id", "entry_guaranteeorg.a_gamount amount", "'集团外' as guaranteetype"});
        DataSet inDataSet2 = guaranteecontractIn2.select(new String[]{"id", "orgName", "bizdate", "entry_guaranteeorg.id", "entry_guaranteeorg.a_gamount amount", "'集团内' as guaranteetype"});
        DataSet outDataSet2 = guaranteecontractOut2.select(new String[]{"id", "orgName", "bizdate", "entry_guaranteeorg.id", "entry_guaranteeorg.a_gamount amount", "'集团外' as guaranteetype"});

        DataSet dataSet = inDataSet.union(outDataSet, inDataSet2, outDataSet2);

        QingData data = null;
        if (i < 200) {
            data = new QingData();
            Map<String, Integer> dataindex = new HashMap<>();
            dataindex.put("id", 0);
            dataindex.put("orgName", 1);
            dataindex.put("bizdate", 2);
            dataindex.put("guaranteetype", 3);
            dataindex.put("amount", 4);
            data.setDataindex(dataindex);

            List<Object[]> rows = new ArrayList<>();
            while (dataSet.hasNext()) {
                Row row = dataSet.next();
                Object[] obj = new Object[5];
                obj[0] = row.getLong("entry_guaranteeorg.id");
                obj[1] = row.getString("orgName");
                Timestamp timestamp = (Timestamp) row.get("bizdate");
                long time = timestamp.getTime();
                obj[2] = time;
                obj[3] = row.getString("guaranteetype");
                obj[4] = row.getBigDecimal("amount");
                rows.add(obj);
            }
            data.setRows(rows);
        }

        return data;
    }

    /**
     * 获取动态表单联查信息
     *
     * @param pageId
     * @param ctrKey
     * @return
     */
    @Override
    public List<QingLinkageInfo> getLinkageInfo(String pageId, String ctrKey) {
        List<QingLinkageInfo> infos = new ArrayList<QingLinkageInfo>();
        QingLinkageInfo info = new QingLinkageInfo();
        Map<String, String> formKey = new HashMap<>();
        AppInfo appInfo = AppMetadataCache.getAppInfo("tda");
        formKey.put("AppId", appInfo.getAppId()); //需要打开的表单所在应用的id
        formKey.put("FormId", "nckd_guaranteecontract2"); //需要打开的表单的id
        formKey.put("System", "IERP");
        formKey.put("CtrKey", ctrKey);
        info.setFormKey(JsonUtil.encodeToString(formKey));
        info.setFormDisplayName("担保合同");//联查到表单的显示名称
        info.setFormPrimaryKey("id");//联查到表单的主键
        infos.add(info);//可以添加多个QingLinkageInfo对象
        this.getView().getPageCache().put("qingViewControlKey", ctrKey);//必要语句!
        return infos;
    }

    /**
     * <p>调用此接口，触发业务逻辑，具体业务联查实现此接口<p/>
     *
     * @param ids    轻分析得到动态表单需要联査的1d的集合
     * @param pageId
     * @param formId
     * @param appId
     */
    @Override
    public void fireLinkageInfo(List<String> ids, String pageId, String formId, String appId) {
        //IQingDataProvider.super.fireLinkageInfo(ids, pageId, formId, appId);
        /*具体的表单打开逻辑，业务自己去实现
        ids:联查到的主键的值
        pageId:触发联査的页面的pageId，可用于找到触发联査的页面: FormView view = (FormView)Sessiomanager.getCurrent().getView(pageId)
        formId:联查到的表单的id
        appId:联查到的表单所在应用的Id
        */

        /*注意: 如果需要使用芒穹的view.showForm 方式打开表单，需要添加以下代码*/
        // 组装 FormShomParaneter(披照业务场景亲实现)
        ReportShowParameter reportShowParameter = new ReportShowParameter();
        reportShowParameter.getOpenStyle().setShowType(ShowType.Modal);
        reportShowParameter.setAppId(appId);
        reportShowParameter.setFormId(formId);//报表标识
        //拿过滤条件，进行取数
        String qFilter = getPageCache().get("qFilter"); //从仪表板进去 拿不到
        //通过此方法拿到过滤参数
        Map<String, Object> filterParam = new HashMap<>();
        // 设置报表过滤条件
        ReportQueryParam reportQueryParam = new ReportQueryParam();
        filterParam.put("id", ids);
        reportQueryParam.setCustomParam(filterParam);
        reportShowParameter.setQueryParam(reportQueryParam);

        /*******************************showForm必要的代码******************************************/
        IFormView view = SessionManager.getCurrent().getView(pageId);
        String ctrKey = this.getView().getPageCache().get("qingViewControlKey");
        if (ctrKey != null) {
            if (view.getControl(ctrKey) instanceof IQingAnalysis) {
                //设计器的场景，直接showForm
                view.showForm(reportShowParameter);
                return;
            }
        }
        //其他场景需要，返回FormShowParameter，由轻分析来 showForm
        this.getView().setClientReturnData(ListShowParameter.toJsonString(reportShowParameter));
        /*******************************showForm必要的代码******************************************/
    }

    @Override
    public void setFilterParameter(String filterParameter) {
        IPageCache pageCache = getPageCache();
        pageCache.put("qFilter", filterParameter);

    }

    @Override
    public String getFilterParameter() {
        return getPageCache().get("qFilter");
    }

    private Date getCurrentDate() {
        Calendar cal = new GregorianCalendar();
//        cal.set(11, 0);
//        cal.set(12, 0);
//        cal.set(13, 0);
//        cal.set(14, 0);
        return cal.getTime();
    }
}
